<?php


namespace app\api\controller\v1\admin;


use app\api\ApiController;
use app\model\ModelMenu;

class Menu extends ApiController
{
    /**
     * 菜单列表
     */
    public function menuList()
    {
        $model = new ModelMenu();
        $data = $model->getMenu([], 'id,name,pid,url,level,status,type');
        $data = recursive_make_tree($data, 'id', 'pid', 'children', 0);
        if ($data) {
            return api_success($data);
        } else {
            return api_list_not_more();
        }
    }

    /**
     * 新增，编辑菜单
     */
    public function addOrEditMenu()
    {
        $info = input('param.');
        $id = $info['id'];
        unset($info['id']);
        if(empty($info['name'])){
            return api_error('请填写完整后提交');
        }

        $m = new ModelMenu();
        if($id){
            $res = $m->isUpdate(true)->save($info,['id' => $id]);
            if($res){return api_success('ok');}else{return api_error('ng');}
        }else{
            $res = $m->save($info);
            if($res){return api_success('ok');}else{return api_error('ng');}
        }
    }

    /**
     * 菜单删除
     */
    public function menuDelete()
    {
        $id = input('id');
        if (empty($id)) {
            return api_param_error();
        }
        $m = new ModelMenu();
        $haveChild = $m->where(['pid' => $id])->field('id')->find();
        if (!empty($haveChild)) {
            return api_error('请先删除下级');
        }
        $res = $m::destroy($id);
        if ($res) {
            return api_success('删除成功');
        } else {
            return api_error('删除失败');
        }
    }
}